package gk.cxd.friday.service.impl;

import gk.cxd.friday.common.constant.UserConstants;
import gk.cxd.friday.common.result.TableDataInfo;
import gk.cxd.friday.model.SysUser;
import gk.cxd.friday.model.vo.SysUserVO;
import gk.cxd.friday.repository.SysUserRepository;
import gk.cxd.friday.service.SysUserService;
import gk.cxd.friday.utils.BeanUtils;
import gk.cxd.friday.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    SysUserRepository sysUserRepository;


    /**
     * 业务层-用户列表的实现
     * @return
     */
    /*@Override
    public List<SysUser> selectSysUserList() {
        return sysUserRepository.findAll();
    }*/
    @Override
    public TableDataInfo selectSysUserList(SysUserVO user, Pageable page) {
        SysUser sysUser = new SysUser();
        //拷贝对象值并忽略空值null和空字符串
        BeanUtils.copyPropertiesIgnoreEmpty(user,sysUser);
        sysUser.setDelFlag("0");
        //创建匹配器，即使用模糊查询的条件
        ExampleMatcher exampleMatcher = ExampleMatcher.matching() //构建对象
                .withMatcher("userName",ExampleMatcher.GenericPropertyMatchers.contains())
                //采用姓名“开始匹配”的方式查询
                .withMatcher("phonenumber",ExampleMatcher.GenericPropertyMatchers.contains());
                //采用姓名“手机号码”的方式查询
        //创建实例
        Example<SysUser> example = Example.of(sysUser,exampleMatcher);
        //查询完后放入分页中
        Page<SysUser> rs = sysUserRepository.findAll(example,page);
        return TableDataInfo.success(rs.toList(), rs.getTotalElements());
    }

    @Override
    public String checkUserNameUnique(String userName) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        return count(sysUser);
    }
    @Override
    public String checkPhoneUnique(SysUserVO userInfo) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userInfo,user);
        return checkUnique(user);
    }
    @Override
    public String checkEmailUnique(SysUserVO userInfo) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userInfo,user);
        return checkUnique(user);
    }
    /**
     * 业务层-新增用户的方法的实现
     */
    @Override
    @Transactional
    public boolean insertUser(SysUserVO user) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(user,sysUser);
        sysUser.setDelFlag("0");
        //新增用户信息
        sysUserRepository.save(sysUser);
        user.setUserId(sysUser.getUserId());
        //新增用户与角色管理
        insertUserRole(user);
        return null != sysUser.getUserId();
    }

    /**
     * 批量删除用户
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        return sysUserRepository.deleteUserByIds(userIds);
    }
    /**
     * 修改用户的方法实现
     */
    @Override
    @Transactional
    public boolean updateUser(SysUserVO user){
        Long userId = user.getUserId();
        Optional<SysUser> op = sysUserRepository.findById(userId);
        if(!op.isPresent()){
            return false;
        }
        //删除用户与角色关联
        sysUserRepository.deleteUserRoleByUserId(userId);
        SysUser sysUser = op.get();
        BeanUtils.copyPropertiesIgnoreNull(user,sysUser);
        //更新用户信息
        sysUserRepository.save(sysUser);
        //新增用户与角色关联
        insertUserRole(user);
        return null != sysUser.getUserId();
    }

    /**
     * 通过用户id查询用户的实现
     */
    @Override
    public SysUser selectUserId(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setDelFlag("0");
        return sysUserRepository.findOne(Example.of(sysUser)).get();
    }
    /**
     * 通过用户名查询用户的实现
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setDelFlag("0");
        Example<SysUser> example=Example.of(sysUser);
        return findOne(example);
    }

    /**
     * 新增用户角色信息
     */
    @Transactional
    public int insertUserRole(SysUserVO user){
        Long [] roles = user.getRoleIds();
        if(StringUtils.isNull(roles) || roles.length == 0){
            return 0;
        }
        Long[] userIds = new Long[roles.length];
        Arrays.fill(userIds,user.getUserId());
        return sysUserRepository.batchInsertUserRole(userIds,roles);
    }

    public String count(SysUser sysUser){
        Example<SysUser> example = Example.of(sysUser);
        long count = sysUserRepository.count(example);
        if(count > 0){
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    public String checkUnique(SysUser user){
        Long userId = StringUtils.isNull(user.getUserId())?1L:user.getUserId();
        Example<SysUser> example = Example.of(user);
        SysUser info = findOne(example);
        if(StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()){
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    public SysUser findOne(Example<SysUser> example){
        List<SysUser> list = sysUserRepository.findAll(example, PageRequest.of(0,1)).toList();
        if(list.isEmpty()){
            return null;
        }
        return list.get(0);
    }


}

